import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/:catchAll(.*)',
      name: 'not-found',
      meta: {
        title: '404',
        requireAuth: false
      },
      component: () => import('../views/404.vue')
    },
    {
      path: '/login',
      name: 'login',
      meta: {
        title: '登录',
        requireAuth: false
      },
      component: () => import('../views/Login.vue')
    },
    {
      path: '/',
      name: 'manage',
      meta: {
        title: '控制台',
        requireAuth: true
      },
      component: () => import('../views/Manage.vue'),
      redirect: '/',
      children: [
        {
          path: '/',
          name: 'home',
          meta: {
            title: '首页',
            requireAuth: true
          },
          component: () => import('../views/Home.vue')
        },
        {
          path: '/user_manage',
          name: 'user_manage',
          meta: {
            title: '用户管理',
            requireAuth: true
          },
          component: () => import('../views/User.vue')
        },
        {
          path: '/role_manage',
          name: 'role_manage',
          meta: {
            title: '角色管理',
            requireAuth: true
          },
          component: () => import('../views/UserRole.vue')
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  const store = useUserStore()
  document.title = to.meta.title + '-后台管理系统'
  if (to.meta.requireAuth) {
    if (store.isLogin) {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

export default router
